<template>
    <div class="editSQL app-container">

      <el-row>
        <el-col :span="14">
          <el-alert title="请输入SQL语句，“USE”和“DROP”语句禁用，有需求请联系管理员" show-icon type="info" :closable="false"></el-alert>
          <el-form :model="checkData" ref="SQLEditForm" :rules="rules">
            <el-form-item label="SQL" label-width="45px" prop="sql_content">
              <!--<el-input :rows="10" type="textarea" v-model="checkData.sql_content" auto-complete="off"-->
                        <!--placeholder="请输入需要执行的SQL语句，多条请分号隔开...">-->
              <!--</el-input>-->
              <editor v-model="checkData.sql_content" @init="editorInit" @setCompletions="setCompletions"></editor>
            </el-form-item>

            <el-form-item label="备注" label-width="45px" prop="remark">
              <el-input :rows="1" type="textarea" v-model="checkData.remark"
                        placeholder="关于SQL用途说明和备注信息...">
              </el-input>
            </el-form-item>

            <el-form-item class="btn-wrapper" label="操作" label-width="45px">
              <el-button type="default" size="small" @click="resetForm">清空</el-button>
              <el-button type="primary" size="small" @click="handleSubmitCheckSQL">提交</el-button>
            </el-form-item>
          </el-form>

        </el-col>
        <el-col :span="9" :offset="1">
          <el-alert title="请选择执行信息" show-icon type="info" :closable="false"></el-alert>

          <el-form :model="checkData" ref="choiceEditForm" :rules="rules">
            <el-form-item label="执行环境" prop="env" label-width="80px">
              <el-select class="select" v-model="checkData.env" placeholder="请选择环境">
                <el-option v-for="env in envs"
                           :label="env.text" :value="env.value" :key="env.value">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="执行库" prop="database" label-width="80px">
              <el-select class="select" v-model="checkData.database" placeholder="请选择环境">
                <el-option v-for="db in dbs"
                           :label="db.name" :value="db.id" :key="db.id">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="审核组" label-width="80px" prop="group">
              <el-select v-model="checkData.group" class="select" placeholder="请选择审核组">
                <el-option v-for="group, index in groups"
                           :label="group.name" :value="group.id" :key="index">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="审核人" label-width="80px" prop="treater">
              <el-select v-model="checkData.treater" class="select" placeholder="请选择审核人">
                <el-option v-for="t, index in treaters"
                           :label="t.name" :value="t.id" :key="index">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>

        </el-col>
      </el-row>

    </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { getUserGroups } from '@/api/users'
  import { getDatabasesList, getTreatersList, SubmitCheckSQL } from '@/api/sqlaudit'
  import editor from './components/editor'

  export default {
    name: 'editSQL',
    components: { editor },
    computed: {
      ...mapGetters({
        userid: 'userid',
        userrole: 'userrole',
        envs: 'envs'
      })
    },
    data() {
      return {
        mysqlHighright: 'alter|and|as|asc|between|count|create|delete|desc|distinct|drop|from|having|in|insert|into|is|join|like|not|on|or|order|select|set|table|union|update|values|where|accessible|action|add|after|algorithm|all|analyze|asensitive|at|authors|auto_increment|autocommit|avg|avg_row_length|before|binary|binlog|both|btree|cache|call|cascade|cascaded|case|catalog_name|chain|change|changed|character|check|checkpoint|checksum|class_origin|client_statistics|close|coalesce|code|collate|collation|collations|column|columns|comment|commit|committed|completion|concurrent|condition|connection|consistent|constraint|contains|continue|contributors|convert|cross|current_date|current_time|current_timestamp|current_user|cursor|data|database|databases|day_hour|day_microsecond|day_minute|day_second|deallocate|dec|declare|default|delay_key_write|delayed|delimiter|des_key_file|describe|deterministic|dev_pop|dev_samp|deviance|directory|disable|discard|distinctrow|div|dual|dumpfile|each|elseif|enable|enclosed|end|ends|engine|engines|enum|errors|escape|escaped|even|event|events|every|execute|exists|exit|explain|extended|fast|fetch|field|fields|first|flush|for|force|foreign|found_rows|full|fulltext|function|general|global|grant|grants|group|groupby_concat|handler|hash|help|high_priority|hosts|hour_microsecond|hour_minute|hour_second|if|ignore|ignore_server_ids|import|index|index_statistics|infile|inner|innodb|inout|insensitive|insert_method|install|interval|invoker|isolation|iterate|key|keys|kill|language|last|leading|leave|left|level|limit|linear|lines|list|load|local|localtime|localtimestamp|lock|logs|low_priority|master|master_heartbeat_period|master_ssl_verify_server_cert|masters|match|max|max_rows|maxvalue|message_text|middleint|migrate|min|min_rows|minute_microsecond|minute_second|mod|mode|modifies|modify|mutex|mysql_errno|natural|next|no|no_write_to_binlog|offline|offset|one|online|open|optimize|option|optionally|out|outer|outfile|pack_keys|parser|partition|partitions|password|phase|plugin|plugins|prepare|preserve|prev|primary|privileges|procedure|processlist|profile|profiles|purge|query|quick|range|read|read_write|reads|real|rebuild|recover|references|regexp|relaylog|release|remove|rename|reorganize|repair|repeatable|replace|acequire|resignal|restrict|resume|return|returns|revoke|right|rlike|rollback|rollup|row|row_format|rtree|savepoint|schedule|schema|schema_name|schemas|second_microsecond|security|sensitive|separator|serializable|server|session|share|show|signal|slave|slow|smallint|snapshot|soname|spatial|specific|sql|sql_big_result|sql_buffer_result|sql_cache|sql_calc_found_rows|sql_no_cache|sql_small_result|sqlexception|sqlstate|sqlwarning|ssl|start|starting|starts|status|std|stddev|stddev_pop|stddev_samp|storage|straight_join|subclass_origin|sum|suspend|table_name|table_statistics|tables|tablespace|temporary|terminated|to|trailing|transaction|trigger|triggers|truncate|uncommitted|undo|uninstall|unique|unlock|upgrade|usage|use|use_frm|user|user_resources|user_statistics|using|utc_date|utc_time|utc_timestamp|value|variables|varying|view|views|warnings|when|while|with|work|write|xa|xor|year_month|zerofill|begin|do|then|else|loop|repeat|by|bool|boolean|bit|blob|decimal|double|enum|float|long|longblob|longtext|medium|mediumblob|mediumint|mediumtext|time|timestamp|tinyblob|tinyint|tinytext|text|bigint|int|int1|int2|int3|int4|int8|integer|float|float4|float8|double|char|varbinary|varchar|varcharacter|precision|date|datetime|year|unsigned|signed|numeric|ucase|lcase|mid|len|round|rank|now|format|coalesce|ifnull|isnull|nvl',
        checkData: {
          database: '',
          treater: '',
          env: 'dev',
          group: '',
          sql_content: '',
          remark: ''
        },
        groups: [],
        treaters: [],
        dbs: [],
        rules: {
          sql_content: [{ required: true, message: '请输入需要提交的SQL语句', trigger: 'blur' }],
          group: [{ required: true, message: '请选择要提交到哪个审核组', trigger: 'blur' }],
          env: [{ required: true, message: '请选择执行环境', trigger: 'blur' }],
          database: [{ required: true, message: '请选择执行库', trigger: 'blur' }],
          treater: [{ required: true, message: '请选择审核人', trigger: 'blur' }],
          remark: [{ required: false }]
        },
        wordList: []
      }
    },
    watch: {
      'checkData.env'(val) {
        this.checkData.database = ''
        this.checkData.group = ''
        this.getDatabaseList({ env: val, page_size: 0 })
      },
      'checkData.group'(val) {
        this.checkData.treater = ''
        this.checkData.group = val
        this.getTreaterList({ group: val, env: this.checkData.env })
      }
    },
    created() {
      this.getWordList()
      this.getGroupList()
      this.getDatabaseList({ env: 'dev', page_size: 0 })
    },
    methods: {
      getWordList() {
        for (const i of this.mysqlHighright.split('|')) {
          this.wordList.push({ 'vl': i, 'meta': '关键字' })
        }
      },
      editorInit: function() {
        require('brace/mode/mysql') // language
        require('brace/theme/xcode')
      },
      setCompletions(editor, session, pos, prefix, callback) {
        callback(null, this.wordList.map(function(word) {
          return {
            caption: word.vl,
            value: word.vl,
            meta: word.meta
          }
        }))
      },
      resetForm() {
        this.checkData = { database: '', treater: '', env: 'dev', group: '' }
        this.$refs['SQLEditForm'].resetFields()
        this.$refs['choiceEditForm'].resetFields()
      },
      getGroupList() {
        getUserGroups(this.userid, { page_size: 0 }).then(
          res => {
            this.groups = res.map(
              item => {
                return { id: item.id, name: item.name }
              })
          })
      },
      getDatabaseList(params) {
        getDatabasesList(params).then(
          res => {
            this.dbs = res.map(
              item => {
                return { id: item.id, name: item.name }
              })
          })
      },
      getTreaterList(data) {
        getTreatersList(data).then(
          res => {
            this.treaters = res.map(
              item => {
                return { id: item.id, name: item.name }
              })
          }).catch(
          () => {
            this.$message.error('获取审核人失败，请重试')
          })
      },
      handleSubmitCheckSQL() {
        this.$refs['SQLEditForm'].validate(
          (valid) => {
            if (!valid) {
              return
            }
            this.$refs['choiceEditForm'].validate(
              (valid) => {
                if (!valid) {
                  return
                }
                SubmitCheckSQL(this.checkData).then(
                  res => {
                    const status = res.status
                    const msg = res.msg
                    if (status === 0) {
                      this.$notify({ title: '成功', message: 'SQL基础检查通过，已经提交等待审核上线',
                        type: 'success', duration: 8000, offset: 32 })
                      this.resetForm()
                    } else if (status === -1 || status === -2 || status === -3) {
                    // } else {
                      this.$notify({ title: '失败', message: msg, type: 'error', duration: 15000, offset: 32 })
                    }
                  })
                  .catch(
                    () => {
                      this.$message.error('SQL提交出错')
                    })
              })
          })
      }
    }
  }
</script>

<style lang="scss" scoped>
.editSQL {
  .btn-wrapper {
    text-align: right;
  }
  .el-alert {
    margin-bottom: 10px;
  }
  .select {
    width: 100%;
  }
}
</style>
